"use client";

import { useEffect } from 'react';
import { useWechatShare } from '@/hooks/useWechatShare';

interface WeChatShareProviderProps {
  title: string;
  description: string;
  imageUrl?: string;
  link?: string;
}

export default function WeChatShareProvider({ 
  title, 
  description, 
  imageUrl = '/logo.png', 
  link 
}: WeChatShareProviderProps) {
  const shareData = {
    title,
    desc: description,
    link: link || (typeof window !== 'undefined' ? window.location.href : ''),
    imgUrl: (() => {
      if (imageUrl.startsWith('http')) return imageUrl;
      if (typeof window !== 'undefined') {
        // 确保相对路径以 / 开头
        const normalizedUrl = imageUrl.startsWith('/') ? imageUrl : `/${imageUrl}`;
        return `${window.location.origin}${normalizedUrl}`;
      }
      return imageUrl;
    })(),
  };

  const { isWechat } = useWechatShare(shareData);

  // 在微信环境中，自动设置页面标题和描述
  useEffect(() => {
    if (isWechat && typeof window !== 'undefined') {
      // 设置页面标题
      document.title = title;
      
      // 设置或更新meta描述
      let metaDescription = document.querySelector('meta[name="description"]');
      if (!metaDescription) {
        metaDescription = document.createElement('meta');
        metaDescription.setAttribute('name', 'description');
        document.head.appendChild(metaDescription);
      }
      metaDescription.setAttribute('content', description);

      // 设置微信专用meta标签
      const setWechatMeta = (property: string, content: string) => {
        let meta = document.querySelector(`meta[property="${property}"]`);
        if (!meta) {
          meta = document.createElement('meta');
          meta.setAttribute('property', property);
          document.head.appendChild(meta);
        }
        meta.setAttribute('content', content);
      };

      setWechatMeta('wechat:title', title);
      setWechatMeta('wechat:description', description);
      setWechatMeta('wechat:image', shareData.imgUrl);
      setWechatMeta('wechat:url', shareData.link);
    }
  }, [isWechat, title, description, shareData.imgUrl, shareData.link]);

  // 这个组件不渲染任何内容，只是提供微信分享功能
  return null;
}
